﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Windows7.Multitouch;
using Windows7.Multitouch.Manipulation;
using Windows7.Multitouch.WPF;

namespace ComicViewer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>Internal Reference for the current PageViewer Control</summary>
        Comic.Viewer.ctlComicViewer _TmpPageViewReference;
        /// <summary>reminder if Init is done</summary>
        private bool _initDone;

        /// <summary>Constructor</summary>
        public MainWindow()
        {
            InitializeComponent(); // basic init for designer-code
            this._initDone = false; // remind init is not complete
            this.Loaded += new RoutedEventHandler(Window_Loaded); // add loaded-handler
        }

        #region add / remove PageViewer Control
        
        /// <summary>Create a PageViewer-Control in the GUI</summary>
        private void _CreatePageViewControl_()
        {
            if (this._TmpPageViewReference == null) // there is no control yet
            {
                // create new control
                Comic.Viewer.ctlComicViewer __viewerControl = new Comic.Viewer.ctlComicViewer();
                // cast MainWindow to Window for passing a reference to the Control
                Window __tmpRef = (Window)this;
                __viewerControl.SetParentWindow(ref __tmpRef);
                // set GUI-Grid Row
                Grid.SetRow(__viewerControl, 1);
                // add to Grid
                this.grdMain.Children.Add(__viewerControl);
                // set margin (0)
                __viewerControl.Margin = new Thickness(0);
                // remind control-reference for later use
                this._TmpPageViewReference = __viewerControl;
            }
        }

        /// <summary>Delete the current PageViewer-Control in the GUI</summary>
        private void _DeletePageViewControl_()
        {
            if (this._TmpPageViewReference != null) // there is a control to delete
            {
                // remove Control from Grid
                this.grdMain.Children.Remove(this._TmpPageViewReference);
                // unregister possible multi-touch events
                if (this._TmpPageViewReference.MultiTouchActive) // only if active
                    this._TmpPageViewReference.MultiTouchActive = false; // deactivate Multi-Touch
                // delete reference
                this._TmpPageViewReference = null;
            }
        }

        #endregion

        /// <summary>Handler if Window is loaded</summary>
        /// <param name="sender">not used</param>
        /// <param name="re">not used</param>
        void Window_Loaded(object sender, RoutedEventArgs re)
        {
            if (!TouchHandler.DigitizerCapabilities.IsMultiTouchReady) // device has no multi-touch
                this.rrbtnPanImageMultiTouch.IsEnabled = false; // lock GUI-Elements
            

            // ToDo: remove - just testcode; do this by user-settings-apply later
            // create a page-viewer-control
            this._CreatePageViewControl_();

            // indicate init is complete
            this._initDone = true;
            // apply use-state state based on current gui-settings
            this._ApplyNavigationControlVisibility_();
            this._ApplyWheelUsageMode_();
            this._ApplyMultitouchState_();

            // load page - Logo as Start-Content...
            Comic.Common.cComicPage __tmpPage = new Comic.Common.cComicPage();
            __tmpPage.PageBannerHtml = string.Empty;
            Uri __tmpUri = new Uri("pack://application:,,,/ComicViewer;component/Grafics/WcrLogo.png", UriKind.RelativeOrAbsolute);
            BitmapSource __tmpImage = new BitmapImage(__tmpUri);
            __tmpPage.PageImage = _BitmapToBitmap_(__tmpImage, "png");
            // load page to GUI
            this._TmpPageViewReference.LoadPage(__tmpPage, false, false);

        }

        /// <summary>required to Convert BitmapSource to Drawing.Bitmap - remove later</summary>
        /// <param name="bitmap"></param>
        /// <param name="imgType"></param>
        /// <returns></returns>
        private System.Drawing.Bitmap _BitmapToBitmap_(BitmapSource bitmap, string imgType)
        {
            BitmapEncoder enc = null;
            System.Drawing.Bitmap oB_cnv = null;
            System.Drawing.Bitmap oB_out = null;

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                switch (imgType.ToLower())
                {
                    case "bmp":
                        enc = new BmpBitmapEncoder();
                        break;
                    case "gif":
                        enc = new GifBitmapEncoder();
                        break;
                    case "jpg":
                        enc = new JpegBitmapEncoder();
                        break;
                    case "png":
                        enc = new PngBitmapEncoder();
                        break;
                    case "tif":
                        enc = new TiffBitmapEncoder();
                        break;
                }
                enc.Frames.Add(BitmapFrame.Create(bitmap));
                enc.Save(ms);

                // MemoryStream to System.Drawing.Bitmap.
                oB_cnv = new System.Drawing.Bitmap(ms);

                // Dereference.
                oB_out = new System.Drawing.Bitmap(oB_cnv);
            }
            return oB_out;
        }   

        // PageView Control remoting

        /// <summary>Apply the View-Mode (comic-browse = SingleTouch | page-touch = Multi-Touch)</summary>
        private void _ApplyMultitouchState_()
        {
            if (!this._initDone) // if not fully initialized
                return; // exit this function
            bool __multiTouchActive = false;
            if (this.rrbtnPanImageMultiTouch.IsEnabled == true) // check if item is enabled
            {
                if (this.rrbtnPanImageMultiTouch.IsChecked != null) // check if item checked-value is not null
                {
                    if (this.rrbtnPanImageMultiTouch.IsChecked == true) // multi-touch is enabled (selected)
                        __multiTouchActive = true;
                }
            }
            // apply result
            if (__multiTouchActive) // multi-touch is enabled
            {
                // set buttons
                this._SetStartRibbonControls_(true);
                // apply settings to control
                this._TmpPageViewReference.MultiTouchActive = true;
                if (this.rchkRotateImage.IsChecked==true)
                    this._TmpPageViewReference.MultiTouchRotate = true; 
                else
                    this._TmpPageViewReference.MultiTouchRotate = false;

                if (this.rchkZoomImage.IsChecked == true)
                    this._TmpPageViewReference.MultiTouchZoom = true;
                else
                    this._TmpPageViewReference.MultiTouchZoom = false;
            }
            else // multi-touch is disabled
            {
                // set buttons
                this._SetStartRibbonControls_(false);
                // apply settings to control
                this._TmpPageViewReference.MultiTouchActive = false;
            }
        }

        /// <summary>apply Visibility-State of Navigation-Elements from GUI to Control</summary>
        private void _ApplyNavigationControlVisibility_()
        {
            if (!this._initDone) // if not fully initialized
                return; // exit this function
            if (this.rtbtnShowControls.IsChecked == true) // if navigation should be displayed
            {
                this._TmpPageViewReference.ShowNavigationControls = true; // set property in control
            }
            else // no navigation should be displayed
            {
                this._TmpPageViewReference.ShowNavigationControls = false; // set property in control
            }
        }

        /// <summary>apply the WheelScroll usage mode to the PageView Control</summary>
        private void _ApplyWheelUsageMode_()
        {
            if (!this._initDone) // if not fully initialized
                return; // exit this function
            if (this.rrbtnWheelZoom.IsChecked == true) // Zoom is active
            {
                this._TmpPageViewReference.UseWheelForZoom = true;
            }
            else // use scroll as default
            {
                this._TmpPageViewReference.UseWheelForZoom = false;
            }
        }

        /// <summary>set Controls in Ribbon based on mode (Single/Multi-Touch Mode)</summary>
        /// <param name="MultiTouchModeActive">TRUE if MultiTouch should be enabled</param>
        private void _SetStartRibbonControls_(bool MultiTouchModeActive)
        {
            // set Enabled-State of Elements in Groups:
            // MultiTouch Controls
            this.rchkZoomImage.IsEnabled = MultiTouchModeActive;
            this.rchkRotateImage.IsEnabled = MultiTouchModeActive;
            // SingeTouch Controls
            this.rbtnZoomIn.IsEnabled = !MultiTouchModeActive;
            this.rbtnZoomOut.IsEnabled = !MultiTouchModeActive;
            this.rbtnZoomReset.IsEnabled = !MultiTouchModeActive;
            this.rrbtnWheelScroll.IsEnabled = !MultiTouchModeActive;
            this.rrbtnWheelZoom.IsEnabled = !MultiTouchModeActive;
        }

        // ribbon events

        /// <summary>MultiTouch Mode entered</summary>
        /// <param name="sender">not used</param>
        /// <param name="e">not used</param>
        private void rrbtnPanImageMultiTouch_Checked(object sender, RoutedEventArgs e)
        {
            this._ApplyMultitouchState_();
        }

        /// <summary>SingleTouch Mode entered</summary>
        /// <param name="sender">not used</param>
        /// <param name="e">not used</param>
        private void rrbtnPanImageSingleTouch_Checked(object sender, RoutedEventArgs e)
        {
            this._ApplyMultitouchState_();
        }

        /// <summary>MultiTouch zoom enabled/disabled</summary>
        /// <param name="sender">not used</param>
        /// <param name="e">not used</param>
        private void rchkZoomImage_Click(object sender, RoutedEventArgs e)
        {
            this._ApplyMultitouchState_();
        }

        /// <summary>MultiTouch rotation enabled/disabled</summary>
        /// <param name="sender">not used</param>
        /// <param name="e">not used</param>
        private void rchkRotateImage_Click(object sender, RoutedEventArgs e)
        {
            this._ApplyMultitouchState_();
        }

        /// <summary>Toggle visibility of Navigation-Elements in PageViewer Control</summary>
        /// <param name="sender">not used</param>
        /// <param name="e">not used</param>
        private void rtbtnShowControls_Click(object sender, RoutedEventArgs e)
        {
            this._ApplyNavigationControlVisibility_();
        }

        /// <summary>Wheel usage "zoom" activated</summary>
        /// <param name="sender">not used</param>
        /// <param name="e">not used</param>
        private void rrbtnWheelZoom_Checked(object sender, RoutedEventArgs e)
        {
            this._ApplyWheelUsageMode_();
        }

        /// <summary>Wheel usage "(vertical) scroll" activated</summary>
        /// <param name="sender">not used</param>
        /// <param name="e">not used</param>
        private void rrbtnWheelScroll_Checked(object sender, RoutedEventArgs e)
        {
            this._ApplyWheelUsageMode_();
        }


        private void rbtnZoomIn_Click(object sender, RoutedEventArgs e)
        {
            this._TmpPageViewReference.ZoomIn();
        }

        private void rbtnZoomOut_Click(object sender, RoutedEventArgs e)
        {
            this._TmpPageViewReference.ZoomOut();
        }

        private void rbtnZoomReset_Click(object sender, RoutedEventArgs e)
        {
            this._TmpPageViewReference.ZoomReset();
        }

    }
}